package com.lujieni.threadpool.controller;

import com.lujieni.threadpool.config.Context;
import com.lujieni.threadpool.context.ContextHolder;
import com.lujieni.threadpool.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.logging.SimpleFormatter;

@RestController
public class HelloController {

    @Autowired
    private HelloService helloService;

    @Autowired
    private ThreadPoolTaskExecutor fuckAsyncPool;

    @GetMapping("/taskRetry")
    public void taskRetry() {
        helloService.taskRetry();
    }



    @GetMapping("/do")
    public String doBusiness() throws InterruptedException {
        helloService.doA();
        helloService.doB();
        return "ok";
    }

    @GetMapping("/shutdown")
    public String shutdown() throws InterruptedException {
        fuckAsyncPool.shutdown();
        return "ok";
    }

    @GetMapping("/sleep/{seconds}")
    public String sleep(@PathVariable(value = "seconds") Integer seconds) {
        Date start = new Date();
        try {
            Thread.sleep(seconds * 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Date end = new Date();
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(start) + "      " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(end);
    }

    /**
     * 另一种传递线程上下文的方法,使用Task
     * @param userCode
     * @return
     */
    @GetMapping("/useTaskDecorate")
    public String useTaskDecorate(String userCode){
        ContextHolder.setContext(new Context(UUID.randomUUID().toString()));
        helloService.useTaskDecorate();
        ContextHolder.clearContext();
        return "ok";
    }

    /**
     * 使用TransmittableThreadLocal传递上下文
     * @return
     */
    @GetMapping("/ttlExecutorService")
    public String ttlExecutorService(){
        helloService.ttlExecutorService();
        return "ok";
    }

    @GetMapping("/getUser")
    public void getUser(){
        helloService.getUser();
    }

    @GetMapping("/execute")
    public String execute() throws InterruptedException {
        helloService.execute();
        return "ok";
    }

    @GetMapping("/result")
    public int result(){
        return helloService.getCount();
    }

}
